<template>
  <div class="container">
    <el-card class="login-box">
      <div style="margin-bottom:20px">用户登录</div>
      <el-form :rules="loginFormRules" :model="admin" ref="loginForm">
        <el-form-item prop="account">
          <el-input
            v-model="admin.account"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item prop="pwd">
          <el-input
            v-model="admin.pwd"
            show-password
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {createNamespacedHelpers} from 'vuex'
const {mapMutations:mapLoginMutations}=createNamespacedHelpers('login')
export default {
    data(){
        const validateAccount=(rule,value,callback)=>{
            if(!/^[a-zA-Z]{5,12}$/.test(value)){
                return callback(new Error('用户名格式有误'))
            }else{
                return callback()
            }
        }
        return{
          admin:{
              account:'',
              pwd:''
          },
          loginFormRules:{
             account:[
                {
                    required:true,
                    message:'账号不能为空',
                    trigger:'blur'
                },
                {
                    validator:validateAccount,
                    trigger:'blur'
                }
             ],
             pwd:[
                {
                   required:true,
                   message:'密码不能为空',
                   trigger:'blur' 
                },
                {
                    min:6,
                    max:12,
                    message:'密码长度为6-12位',
                    trigger:'blur'
                }
             ]
          }
        }
    },
    methods:{
        ...mapLoginMutations(['SET_USER']),
        login(){
            this.$refs.loginForm.validate(async valid=>{
                if(valid){
                     const result=await this.$api.loginModule.loginApi(this.admin)
                     if(result.code==200){
                        this.$message.success(result.message)
                        console.log('result',result.data);
                        this.SET_USER(result.data)
                        this.$router.push('/')
                      }else{
                        tis.$message.error(result.message)
                      }
                }
            })
           
        }
    }
}
</script>

<style lang="scss" scoped>
.container {
  width: 100vw;
  height: 100vh;
  background-image: url("../assets/bg.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  .login-box {
    position: absolute;
    right: 100px;
    top: 200px;
    width: 400px;
    border-radius: 15px;
    .el-button {
      width: 360px;
    }
  }
}
</style>